/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.cliente;

import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 *
 * @author Anderson
 */
public class ArquivoHandler {

    private File hospedesFile, reservasFile, hoteisFile;
    private FileWriter fileWriter;
    private BufferedWriter fileBufferedWriter;
    private BufferedReader fileBufferedReader;
    private DataInputStream inputStream;
    private static final String SEPARATOR = System.getProperty("line.separator");

    public ArquivoHandler() throws IOException {
        this.hospedesFile = new File("hospedes.txt");
        if (!this.hospedesFile.exists()) {
            this.hospedesFile.createNewFile();
        }
        /*
        this.reservasFile = new File("reservas.txt");
        if (!this.reservasFile.exists()) {
        this.reservasFile.createNewFile();
        }
         */
        this.hoteisFile = new File("hoteis.txt");
        if (!this.hoteisFile.exists()) {
            this.hoteisFile.createNewFile();
        }

    }

    //----------- Hospede Functions ------------
    public boolean saveHospede(Hospede hospede) throws IOException {
        if ((getHospede(hospede.getCPF())) == null) {


            try {
                fileWriter = new FileWriter(hospedesFile, true);
                fileBufferedWriter = new BufferedWriter(fileWriter);
                fileBufferedWriter.write(
                        hospede.getNome() + "-"
                        + hospede.getCPF() + "-"
                        + hospede.getEndereco() + "-"
                        + hospede.getTelefone() + "-"
                        + hospede.getEmail() + SEPARATOR);
                fileBufferedWriter.close();
                fileWriter.close();

            } catch (IOException e) {
                System.out.print("Erro salvando hóspede: " + e.getMessage() + SEPARATOR);
            }

        } else {
            System.out.print("Cliente já existe" + SEPARATOR);
            return false;
        }
        return true;


    }

    public Hospede getHospede(String CPF) throws IOException {
        String line = null;
        Hospede hospede = null;

        try {

            FileInputStream fileInputStream = new FileInputStream(hospedesFile);
            DataInputStream dataInputStream = new DataInputStream(fileInputStream);

            fileBufferedReader = new BufferedReader(new InputStreamReader(dataInputStream));

            while ((line = fileBufferedReader.readLine()) != null) {
                String item[] = line.split("-");
                if (item[1].equals(CPF)) {
                    if (item.length == 5) {
                        System.out.print("Cliente Achado" + SEPARATOR);
                        //hospede sem historico no hotel
                        hospede = new Hospede(item[0], item[1], item[2], item[3], item[4]);

                        return hospede;
                    } else {
                        System.out.print("Cliente Achado" + SEPARATOR);
                        //hospede que tem historico no hotel
                        hospede = new Hospede(item[0], item[1], item[2], item[3], item[4],
                                item[5], item[6], Integer.parseInt(item[7]), item[8]);

                        return hospede;
                    }

                }
            }


            fileBufferedReader.close();


        } catch (IOException e) {
            System.out.print("Erro pegando hospede: " + e.getMessage() + SEPARATOR);
        }

        if (line == null) {
            System.out.print("Não Existe cliente com esse CPF!" + SEPARATOR);
        }

        return null;
    }

    public List<Hospede> getAllHospedes() throws IOException {
        List<Hospede> hospedes = new ArrayList();

        String line = null;
        Hospede hospede = null;

        try {

            FileInputStream fileInputStream = new FileInputStream(hospedesFile);

            fileBufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

            while ((line = fileBufferedReader.readLine()) != null) {

                String item[] = line.split("-");

                if (item.length == 5) {
                    //hospede sem historico no hotel
                    hospede = new Hospede(item[0], item[1], item[2], item[3], item[4]);

                    hospedes.add(hospede);
                } else {
                    //hospede que tem historico no hotel
                    hospede = new Hospede(item[0], item[1], item[2], item[3], item[4],
                            item[5], item[6], Integer.parseInt(item[7]), item[8]);

                    hospedes.add(hospede);
                }

            }
            fileBufferedReader.close();
            return hospedes;
        } catch (IOException e) {
            System.out.print("Erro pegando listagem de hospedes: " + e.getMessage() + SEPARATOR);
        }

        fileBufferedReader.close();
        return hospedes;
    }

    public void removeHospede(String CPF) throws IOException {
        String line = null;

        if (getHospede(CPF) != null) {


            FileInputStream fileInputStream = new FileInputStream(hospedesFile);
            DataInputStream dataInputStream = new DataInputStream(fileInputStream);
            fileBufferedReader = new BufferedReader(new InputStreamReader(dataInputStream));


            File tempFile = new File("tempHospedes.txt");
            tempFile.createNewFile();

            fileWriter = new FileWriter(tempFile, true);
            fileBufferedWriter = new BufferedWriter(fileWriter);



            while ((line = fileBufferedReader.readLine()) != null) {
                String item[] = line.split("-");
                if (!(item[1].equals(CPF))) {
                    System.out.print(line + SEPARATOR);
                    fileBufferedWriter.write(line + SEPARATOR);
                    fileBufferedWriter.flush();
                }
            }

            if (hospedesFile.delete()) {
                System.out.print("deletado \n");
                hospedesFile = new File("hospedes.txt");
                System.out.print("novo nome \n");
                tempFile.renameTo(hospedesFile);
                System.out.print("renomeado \n");

            }

            fileWriter.close();
            fileBufferedWriter.close();
            fileBufferedReader.close();

        } else {
            System.out.print("Não Existe Cliente com este CPF para remoção" + SEPARATOR);

        }

    }

    public void editLastStayHospede(String CPF, Reserva reserva) throws IOException {
        String line = null;

        if (getHospede(CPF) != null) {


            FileInputStream fileInputStream = new FileInputStream(hospedesFile);
            DataInputStream dataInputStream = new DataInputStream(fileInputStream);
            fileBufferedReader = new BufferedReader(new InputStreamReader(dataInputStream));


            File tempFile = new File("tempHospedes.txt");
            tempFile.createNewFile();

            fileWriter = new FileWriter(tempFile, true);
            fileBufferedWriter = new BufferedWriter(fileWriter);



            while ((line = fileBufferedReader.readLine()) != null) {
                String item[] = line.split("-");
                if (!(item[1].equals(CPF))) {
                    System.out.print(line + SEPARATOR);
                    fileBufferedWriter.write(line + SEPARATOR);
                    fileBufferedWriter.flush();
                } else {
                    fileBufferedWriter.write(
                            line
                            + reserva.getDataInicioDiaria() + "-"
                            + reserva.getDataFimDiaria() + "+"
                            + reserva.getQuarto() + "-"
                            + reserva.getHotel().getNome() + "-"
                            + SEPARATOR);
                    fileBufferedWriter.flush();
                }
            }

            if (hospedesFile.delete()) {
                System.out.print("deletado \n");
                hospedesFile = new File("hospedes.txt");
                System.out.print("novo nome \n");
                tempFile.renameTo(hospedesFile);
                System.out.print("renomeado \n");

            }

            fileWriter.close();
            fileBufferedWriter.close();
            fileBufferedReader.close();

        } else {
            System.out.print("Não Existe Cliente com este CPF para edição" + SEPARATOR);

        }
    }

    //----------- Hotel Functions ---------------
    public boolean saveHotel(Hotel hotel) throws IOException {
        if ((getHotel(hotel.getNome())) == null) {
            try {
                fileWriter = new FileWriter(hoteisFile, true);
                fileBufferedWriter = new BufferedWriter(fileWriter);
                fileBufferedWriter.write(
                        hotel.getNome() + "-"
                        + hotel.getEndereco() + "-"
                        + hotel.getNomeGerente() + "-"
                        + hotel.getQuantidadeQuartos()
                        + SEPARATOR);
                fileBufferedWriter.close();
                fileWriter.close();

                File f = new File(hotel.getNome());
                f.mkdir();
                f = null;
                f = new File(hotel.getNome().toLowerCase() + "/reservas.txt");
                f.createNewFile();
            } catch (IOException e) {
                System.out.print("Erro salvando hotel: " + e.getMessage() + SEPARATOR);
            }

        } else {
            System.out.print("Hotel já existe" + SEPARATOR);
            return false;
        }
        return true;
    }

    public Hotel getHotel(String nome) throws IOException {
        String line = null;
        Hotel hotel = null;
        try {

            FileInputStream fileInputStream = new FileInputStream(hoteisFile);
            DataInputStream dataInputStream = new DataInputStream(fileInputStream);

            fileBufferedReader = new BufferedReader(new InputStreamReader(dataInputStream));

            while ((line = fileBufferedReader.readLine()) != null) {
                String item[] = line.split("-");
                if (item[0].equals(nome)) {

                    System.out.print("Hotel Achado" + SEPARATOR);

                    hotel = new Hotel(item[0], item[1], item[2], Integer.parseInt(item[3]));
                    fileBufferedReader.close();
                    return hotel;
                }
            }

        } catch (IOException e) {
            System.out.print("Erro pegando hotel: " + e.getMessage() + SEPARATOR);
        }

        if (line == null) {
            System.out.print("Não Existe hotel com esse nome" + SEPARATOR);
        }

        return null;


    }

    public List<Hotel> getAllHoteis() throws IOException {
        String line = null;
        List<Hotel> hoteis = new ArrayList();
        Hotel hotel = null;
        try {

            FileInputStream fileInputStream = new FileInputStream(hoteisFile);

            fileBufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

            while ((line = fileBufferedReader.readLine()) != null) {
                String item[] = line.split("-");

                hotel = new Hotel(item[0], item[1], item[2], Integer.parseInt(item[3]));
                hoteis.add(hotel);
            }
            fileBufferedReader.close();
            return hoteis;
        } catch (IOException e) {
            System.out.print("Erro pegando todos hoteis: " + e.getMessage() + SEPARATOR);
        }

        if (line == null) {
            System.out.print("Não Existe hoteis cadastrados" + SEPARATOR);
        }

        return hoteis;
    }

    public boolean removeHotel(String nome) throws IOException {
        String line = null;

        if (getHotel(nome) != null) {


            FileInputStream fileInputStream = new FileInputStream(hoteisFile);
            DataInputStream dataInputStream = new DataInputStream(fileInputStream);
            fileBufferedReader = new BufferedReader(new InputStreamReader(dataInputStream));


            File tempFile = new File("tempHoteis.txt");
            tempFile.createNewFile();
            fileWriter = new FileWriter(tempFile, true);
            fileBufferedWriter = new BufferedWriter(fileWriter);



            while ((line = fileBufferedReader.readLine()) != null) {
                String item[] = line.split("-");
                if (!(item[1].equals(nome))) {
                    fileBufferedWriter.write(line + SEPARATOR);
                    fileBufferedWriter.flush();
                }
            }

            if (hoteisFile.delete()) {
                hospedesFile = new File("hoteis.txt");
                tempFile.renameTo(hoteisFile);
            }


        } else {
            System.out.print("Não Existe Hotel com este nome para remoÃ§Ã£o" + SEPARATOR);
            return false;
        }

        fileWriter.close();
        fileBufferedWriter.close();
        fileBufferedReader.close();
        return true;
    }

    //----------- Reserva Functions -------------
    public boolean saveReserva(Reserva reserva, String CPF) throws IOException, Exception {
        if ((getHospede(CPF) != null)) {
            if (((getReserva(reserva.getHotel().getNome(), CPF)) == null)) {
                if (checkReserva(reserva.getDataInicioDiaria(), reserva.getDataFimDiaria(), reserva.getQuarto(), reserva.getHotel().getNome())) {
                    try {
                        fileWriter = new FileWriter(reservasFile, true);
                        fileBufferedWriter = new BufferedWriter(fileWriter);
                        fileBufferedWriter.write(
                                reserva.getDataInicioDiaria() + "-"
                                + reserva.getDataFimDiaria() + "-"
                                + reserva.getQuarto() + "-"
                                + CPF
                                + SEPARATOR);

                        fileBufferedWriter.close();
                        fileWriter.close();

                    } catch (IOException e) {
                        System.out.print("Erro salvando Reserva: " + e.getMessage() + SEPARATOR);
                    }
                } else {
                    System.out.print("Quarto com dia já reservado" + SEPARATOR);
                    return false;
                }

            } else {
                System.out.print("Reserva desse cliente ja existe" + SEPARATOR);
                return false;
            }
        } else {
            System.out.print("Cliente nao possui cadastro para fazer reserva" + SEPARATOR);
            return false;
        }
        return true;
    }

    public Reserva getReserva(String nomeHotel, String CPF) throws IOException, Exception {
        String line = null;
        Reserva reserva = null;
        try {
            reservasFile = new File(nomeHotel.toLowerCase() + "/reservas.txt");

            FileInputStream fileInputStream = new FileInputStream(reservasFile);
            DataInputStream dataInputStream = new DataInputStream(fileInputStream);

            fileBufferedReader = new BufferedReader(new InputStreamReader(dataInputStream));

            while ((line = fileBufferedReader.readLine()) != null) {
                String item[] = line.split("-");
                if (item[3].equals(CPF)) {

                    System.out.print("Reserva Achada" + SEPARATOR);

                    reserva = new Reserva(getHospede(item[3]), getHotel(nomeHotel),
                            item[0], item[1], Integer.parseInt(item[2]));
                    fileBufferedReader.close();
                    return reserva;
                }
            }
        } catch (IOException e) {
            System.out.print("Erro pegando reserva: " + e.getMessage() + SEPARATOR);
        }
        if (line == null) {
            System.out.print("Não Existe reserva com esses parametros!" + SEPARATOR);
        }

        return null;
    }

    public List<Reserva> getAllReservaFromHotel(String nomeHotel) throws IOException, Exception {
        List<Reserva> reservas = new ArrayList();
        Reserva reserva = null;
        String line = null;
        try {
            reservasFile = new File(nomeHotel.toLowerCase() + "/reservas.txt");

            FileInputStream fileInputStream = new FileInputStream(reservasFile);
            fileBufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

            while ((line = fileBufferedReader.readLine()) != null) {
                String item[] = line.split("-");
                reserva = new Reserva(getHospede(item[3]), getHotel(nomeHotel),
                        item[0], item[1], Integer.parseInt(item[2]));

                reservas.add(reserva);
            }
            fileBufferedReader.close();
            return reservas;

        } catch (IOException e) {
            System.out.print("A listagem de reservas do Hotel" + nomeHotel
                    + "deu o erro: " + e.getMessage());
        }

        return reservas;
    }

    public boolean checkReserva(String dataInicio, String dataFim, int quarto, String nomeHotel) throws IOException, ParseException {
        String line = null;
        String quartoString = String.valueOf(quarto);
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        Date dataIn = (Date) format.parse(dataInicio);
        Date dataFi = (Date) format.parse(dataFim);

        try {
            reservasFile = new File(nomeHotel.toLowerCase() + "/reservas.txt");
            FileInputStream fileInputStream = new FileInputStream(reservasFile);

            fileBufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

            while ((line = fileBufferedReader.readLine()) != null) {
                String item[] = line.split("-");

                if (item[2].equals(quartoString)) {

                    Date di = (Date) format.parse(item[0]);
                    Date df = (Date) format.parse(item[1]);

                    System.out.print("checando colisao de datas" + SEPARATOR + di.compareTo(dataFi) + " " + df.compareTo(dataIn));
                    if ((di.compareTo(dataFi) < 0) && (df.compareTo(dataIn) > 0)) {
                        System.out.print("colisao de datas" + SEPARATOR);
                        fileBufferedReader.close();
                        return false;
                    }

                }
            }

        } catch (IOException e) {
            System.out.print("Erro Checando Reservas!!" + e.getMessage());
        }
        fileBufferedReader.close();
        return true;

    }

    public boolean payReserva(int quarto, String CPF, String hotelNome) throws IOException, Exception {
        Reserva reserva = getReserva(hotelNome, CPF);
        if (reserva != null) {
            editLastStayHospede(CPF, null);
            return true;
        } else {
            return false;
        }

    }

    public boolean extendReserva(Reserva reserva, String dataExtendida) throws Exception, IOException {
        //Date date = Calendar.getInstance().getTime();
        //DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        //String today = formatter.format(date);
        String line = null;

        if (checkReserva(reserva.getDataFimDiaria(), dataExtendida, reserva.getQuarto(), reserva.getHotel().getNome())) {
            reservasFile = new File(reserva.getHotel().getNome() + "/reservas.txt");
            FileInputStream fileInputStream = new FileInputStream(reservasFile);

            fileBufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

            File tempFile = new File(reserva.getHotel().getNome() + "/tempReservas.txt");
            tempFile.createNewFile();
            fileWriter = new FileWriter(tempFile, true);
            fileBufferedWriter = new BufferedWriter(fileWriter);

            while ((line = fileBufferedReader.readLine()) != null) {
                String item[] = line.split("-");
                if (!(item[3].equals(reserva.getHospede().getCPF()))) {
                    fileBufferedWriter.write(line + SEPARATOR);
                    fileBufferedWriter.flush();
                } else {
                    fileBufferedWriter.write(item[0] + "-"
                            + dataExtendida + "-"
                            + item[2] + "-"
                            + item[3]
                            + SEPARATOR);
                    fileBufferedWriter.flush();

                    if (reservasFile.delete()) {
                        reservasFile = new File(reserva.getHotel().getNome() + "/reservas.txt");
                        tempFile.renameTo(reservasFile);

                    }
                }

            }
            return true;

        }

        return false;
    }

    public boolean extendReservaAnotherRoom(Reserva reserva, String dataExtendida) throws IOException, Exception {
        Date date = Calendar.getInstance().getTime();
        DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        String today = formatter.format(date);
        String line = null;
        int roomCount = reserva.getHotel().getQuantidadeQuartos();
        for (int x = 1; x <= roomCount; x++) {
            if (checkReserva(today, dataExtendida, x, reserva.getHotel().getNome())) {
                reservasFile = new File(reserva.getHotel().getNome() + "/reservas.txt");
                FileInputStream fileInputStream = new FileInputStream(reservasFile);

                fileBufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

                File tempFile = new File(reserva.getHotel().getNome() + "/tempReservas.txt");
                tempFile.createNewFile();
                fileWriter = new FileWriter(tempFile, true);
                fileBufferedWriter = new BufferedWriter(fileWriter);

                while ((line = fileBufferedReader.readLine()) != null) {
                    String item[] = line.split("-");
                    if (!(item[3].equals(reserva.getHospede().getCPF()))) {
                        fileBufferedWriter.write(line + SEPARATOR);
                        fileBufferedWriter.flush();
                    } else {
                        fileBufferedWriter.write(item[0] + "-"
                                + dataExtendida + "-"
                                + String.valueOf(x) + "-"
                                + item[3]
                                + SEPARATOR);
                        fileBufferedWriter.flush();

                        if (reservasFile.delete()) {
                            reservasFile = new File(reserva.getHotel().getNome() + "/reservas.txt");
                            tempFile.renameTo(reservasFile);

                        }
                    }

                }
                return true;

            }
        }

        return false;
    }
}
